package me.zhengjie.modules.workorder.rest;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import me.zhengjie.aop.log.Log;
import me.zhengjie.modules.system.common.EnumWorkorderSource;
import me.zhengjie.modules.system.common.EnumWorkorderStatus;
import me.zhengjie.modules.workorder.domain.TWorkOrder;
import me.zhengjie.modules.workorder.service.TWorkOrderService;
import me.zhengjie.modules.workorder.service.dto.TWorkOrderQueryCriteria;
import me.zhengjie.modules.workorder.service.dto.TWorkOrderQueryCriteriaEx;
import me.zhengjie.utils.*;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;


/**
* @author zcw
* @date 2019-08-13
*/
@RestController
@RequestMapping("api")
public class TWorkOrderController {

    @Autowired
    private TWorkOrderService tWorkOrderService;

    @SuppressWarnings({ "unchecked", "rawtypes" })
	@Log("查询TWorkOrder")
    @GetMapping(value = "/tWorkOrder")
    //@PreAuthorize("hasAnyRole('ADMIN','TWORKORDER_ALL','TWORKORDER_SELECT')")
    public ResponseEntity getTWorkOrders(TWorkOrderQueryCriteria criteria, Pageable pageable){
        return new ResponseEntity(tWorkOrderService.queryAll(criteria,pageable),HttpStatus.OK);
    }

    @SuppressWarnings({ "unchecked", "rawtypes" })
    @Log("查询TWorkOrder")
    @GetMapping(value = "/tWorkOrder/toclose")
    //@PreAuthorize("hasAnyRole('ADMIN','TWORKORDER_ALL','TWORKORDER_SELECT')")
    public ResponseEntity getTWorkOrdersToclose(TWorkOrderQueryCriteria criteria, Pageable pageable){
        return new ResponseEntity(tWorkOrderService.queryAll(criteria,pageable),HttpStatus.OK);
    }

    @SuppressWarnings({ "unchecked", "rawtypes" })
	@Log("新增TWorkOrder")
    @PostMapping(value = "/tWorkOrder")
    //@PreAuthorize("hasAnyRole('ADMIN','TWORKORDER_ALL','TWORKORDER_CREATE')")
    public ResponseEntity create(@Validated @RequestBody TWorkOrder resources){
        return new ResponseEntity(tWorkOrderService.create(resources),HttpStatus.CREATED);
    }

    @SuppressWarnings("rawtypes")
    @Log("修改TWorkOrder")
    @PutMapping(value = "/tWorkOrder")
    //@PreAuthorize("hasAnyRole('ADMIN','TWORKORDER_ALL','TWORKORDER_EDIT')")
    public ResponseEntity update(@Validated @RequestBody TWorkOrder resources){
        tWorkOrderService.updateBeforeAssign(resources);
        return new ResponseEntity(HttpStatus.NO_CONTENT);
    }

    @SuppressWarnings("rawtypes")
	@Log("删除TWorkOrder")
    @DeleteMapping(value = "/tWorkOrder/{id}")
    //@PreAuthorize("hasAnyRole('ADMIN','TWORKORDER_ALL','TWORKORDER_DELETE')")
    public ResponseEntity delete(@PathVariable Long id){
        tWorkOrderService.delete(id);
        return new ResponseEntity(HttpStatus.OK);
    }
    
    @SuppressWarnings("rawtypes")
    @Log("派单TWorkOrder")
    @PostMapping(value = "/tWorkOrder/assign")
    //@PreAuthorize("hasAnyRole('ADMIN','TWORKORDER_ALL','TWORKORDER_EDIT')")
    public ResponseEntity assign(@Validated @RequestBody TWorkOrder resources){
        resources.setAssignOperator(SecurityUtils.getName()); //分派人
        resources.setAssignTime(new Timestamp(System.currentTimeMillis()));
        resources.setStatus(EnumWorkorderStatus.DISPATCHED.getValue());  //获取证书

        tWorkOrderService.assign(resources);
        return new ResponseEntity(HttpStatus.NO_CONTENT);
    }

    @SuppressWarnings("rawtypes")
    @Log("批量派单TWorkOrder")
    @PostMapping(value = "/tWorkOrder/batchAssign")
    //@PreAuthorize("hasAnyRole('ADMIN','TWORKORDER_ALL','TWORKORDER_EDIT')")
    public ResponseEntity batchAssign(@Validated @RequestBody TWorkOrder resources){
        resources.setAssignOperator(SecurityUtils.getName()); //分派人
        resources.setAssignTime(new Timestamp(System.currentTimeMillis()));
        resources.setStatus(EnumWorkorderStatus.DISPATCHED.getValue());  //获取证书

        tWorkOrderService.batchAssign(resources);
        return new ResponseEntity(HttpStatus.NO_CONTENT);
    }

    @SuppressWarnings("rawtypes")
	@Log("拒单TWorkOrder")
    @PostMapping(value = "/tWorkOrder/refuse")
    //@PreAuthorize("hasAnyRole('ADMIN','TWORKORDER_ALL','TWORKORDER_EDIT')")
    public ResponseEntity refuse(@Validated @RequestBody TWorkOrder resources){
    	tWorkOrderService.refuse(resources);
        return new ResponseEntity(HttpStatus.NO_CONTENT);
    }
    
    @SuppressWarnings("rawtypes")
	@Log("维修TWorkOrder")
    @PostMapping(value = "/tWorkOrder/repair")
    //@PreAuthorize("hasAnyRole('ADMIN','TWORKORDER_ALL','TWORKORDER_EDIT')")
    public ResponseEntity repair(@Validated @RequestBody TWorkOrder resources){
    	tWorkOrderService.repair(resources.getId());
        return new ResponseEntity(HttpStatus.NO_CONTENT);
    }

    @SuppressWarnings("rawtypes")
    @Log("服务商月账单")
    @GetMapping(value = "/tWorkOrder/supplierreport")
    //@PreAuthorize("hasAnyRole('ADMIN','TWORKORDER_ALL','TWORKORDER_EDIT')")
    public ResponseEntity supplierReport(HttpServletRequest request, Pageable pageable){
        TWorkOrderQueryCriteriaEx criteria = parseQuery(request);

        Page<java.util.Map<?,?>> page = tWorkOrderService.queryWorkorderReport(criteria,pageable);
        JSONArray array = new JSONArray();

        for(java.util.Map<?,?> order: page.getContent()) {
            JSONObject obj = new JSONObject();
            obj.put("orderCode", order.get("orderCode")); //编码
            obj.put("supplierName",order.get("supplierName")); //客户名称1
            obj.put("major", order.get("major"));
            obj.put("level", order.get("level"));
            obj.put("realServiceTime", order.get("realServiceTime"));
            obj.put("taskTitle", order.get("taskTitle"));
            obj.put("taskAddr", order.get("taskAddr"));
            obj.put("money", Long.valueOf((String)order.get("realServiceTime"))*((BigInteger)order.get("customerCost")).intValue());
            obj.put("evaluateTime", DateUtil.parseDateToStr((java.util.Date)order.get("evaluateTime"), "yyyy-MM-dd"));
            array.add(obj);
        }

        return new ResponseEntity(PageUtil.toPageWithContent(page,array),HttpStatus.OK);
    }


    @SuppressWarnings("rawtypes")
    @GetMapping(value = "/tWorkOrder/supplierreport/export")
    //@PreAuthorize("hasAnyRole('ADMIN','TWORKORDER_ALL','TWORKORDER_EDIT')")
    public void supplierReportExport(HttpServletRequest request, HttpServletResponse response){
        try {
            TWorkOrderQueryCriteriaEx criteria = parseQuery(request);

            List<java.util.Map<?,?>> page = tWorkOrderService.queryWorkorderReport(criteria);
            JSONArray array = new JSONArray();

            XSSFWorkbook wb = new XSSFWorkbook(this.getClass().getResourceAsStream("/supplier.xlsx"));
            //创建表头等
            XSSFSheet sheet = wb.getSheetAt(0);
            //wb.setSheetName(0, "供应商评价");
            //创建行
            Integer flag = 1;
            if (page.size() > 0) {
                sheet.shiftRows(flag, flag + page.size(), page.size(), true, false);
                for (int i = 0; i < page.size(); i++) {
                    XSSFRow row = sheet.createRow(flag + i);
                    java.util.Map<?,?> order = page.get(i);
                    row.createCell(0).setCellValue((String)order.get("orderCode"));
                    row.createCell(1).setCellValue((String)order.get("supplierName"));
                    row.createCell(2).setCellValue((String)order.get("taskTitle"));
                    row.createCell(3).setCellValue((String)order.get("taskAddr"));
                    row.createCell(4).setCellValue((String)order.get("major"));
                    row.createCell(5).setCellValue((String)order.get("level"));
                    row.createCell(6).setCellValue((String)order.get("orderCode"));
                    String realServiceTime = (String)order.get("realServiceTime");
                    row.createCell(7).setCellValue( Double.valueOf(realServiceTime) * ((BigInteger)order.get("customerCost")).intValue());
                    row.createCell(8).setCellValue(DateUtil.parseDateToStr((java.util.Date)order.get("evaluateTime"), "yyyy-MM-dd"));
                }
            }

            ServletOutputStream output = response.getOutputStream();
            response.setHeader("Content-disposition", "attachment; filename=Info.xls");
            response.setContentType("application/msexcel");
            wb.write(output);
            output.close();
        } catch(Exception ex) {
            ex.printStackTrace();
        }
    }

    private TWorkOrderQueryCriteriaEx parseQuery(HttpServletRequest request) {
        TWorkOrderQueryCriteriaEx criteria = new TWorkOrderQueryCriteriaEx();
        List<Integer> statuses = new ArrayList<Integer>();
        statuses.add(EnumWorkorderStatus.EVAlUATED.getValue());
        statuses.add(EnumWorkorderStatus.CLOSED.getValue());
        criteria.setStatus(statuses);  //只查询符合状态的订单

        String customerName = request.getParameter("customerName");
        if(!StringUtils.isEmpty(customerName)) {
            criteria.setCustomerName(customerName);
        }

        String orderCode = request.getParameter("orderCode");
        if(!StringUtils.isEmpty(orderCode)) {
            criteria.setOrderCode(orderCode);
        }

        String supplierName = request.getParameter("supplierName");
        if (!StringUtils.isEmpty(supplierName)) {
            criteria.setSupplierName(supplierName);
        }

        String orderSource = request.getParameter("orderSource");
        if(!StringUtils.isEmpty(orderSource)) {
            criteria.setOrderSource(Integer.valueOf(orderSource));
        }else{
            criteria.setOrderSource(EnumWorkorderSource.ENUM_WORKORDER_SOURCE_TASK.getValue());
        }

        String reportDate = request.getParameter("reportDate");
        if(!StringUtils.isEmpty(reportDate)) { //yyyy-MM
            java.util.Date begin = DateUtil.parseStrToDate(reportDate+"-01", "yyyy-MM-dd");
            java.util.Date end = DateUtil.addDate(begin,0, 1,0,0,0,0,0);
            criteria.setEvaluateTimeBegin(DateUtil.parseDateToStr(begin, "yyyy-MM-dd"));
            criteria.setEvaluateTimeEnd(DateUtil.parseDateToStr(end, "yyyy-MM-dd"));
        }
        return criteria;
    }

    @SuppressWarnings("rawtypes")
    @GetMapping(value = "/tWorkOrder/customerreport/export")
    //@PreAuthorize("hasAnyRole('ADMIN','TWORKORDER_ALL','TWORKORDER_EDIT')")
    public void customerReportExport(HttpServletRequest request, HttpServletResponse response){
        try {
            TWorkOrderQueryCriteriaEx criteria = parseQuery(request);

            List<java.util.Map<?,?>> page = tWorkOrderService.queryWorkorderReport(criteria);
            JSONArray array = new JSONArray();

            XSSFWorkbook wb = new XSSFWorkbook(this.getClass().getResourceAsStream("/customer.xlsx"));
            //创建表头等
            XSSFSheet sheet = wb.getSheetAt(0);
            //wb.setSheetName(0, "供应商评价");
            //创建行
            Integer flag = 1;
            if (page.size() > 0) {
                sheet.shiftRows(flag, flag + page.size(), page.size(), true, false);
                for (int i = 0; i < page.size(); i++) {
                    XSSFRow row = sheet.createRow(flag + i);
                    java.util.Map<?,?> order = page.get(i);
                    row.createCell(0).setCellValue((String)order.get("orderCode"));
                    row.createCell(1).setCellValue((String)order.get("customerName"));
                    row.createCell(2).setCellValue((String)order.get("taskTitle"));
                    row.createCell(3).setCellValue((String)order.get("taskAddr"));
                    row.createCell(4).setCellValue((String)order.get("major"));
                    row.createCell(5).setCellValue((String)order.get("level"));
                    row.createCell(6).setCellValue((String)order.get("orderCode"));
                    String realServiceTime = (String)order.get("realServiceTime");
                    row.createCell(7).setCellValue( Double.valueOf(realServiceTime) * ((BigInteger)order.get("customerCost")).intValue());
                    row.createCell(8).setCellValue(DateUtil.parseDateToStr((java.util.Date)order.get("evaluateTime"), "yyyy-MM-dd"));
                }
            }

            ServletOutputStream output = response.getOutputStream();
            response.setHeader("Content-disposition", "attachment; filename=Info.xls");
            response.setContentType("application/msexcel");
            wb.write(output);
            output.close();
        } catch(Exception ex) {
            ex.printStackTrace();
        }
    }


    @SuppressWarnings("rawtypes")
    @Log("服务商月账单")
    @GetMapping(value = "/tWorkOrder/customerreport")
    //@PreAuthorize("hasAnyRole('ADMIN','TWORKORDER_ALL','TWORKORDER_EDIT')")
    public ResponseEntity customerReport(HttpServletRequest request, Pageable pageable){
        TWorkOrderQueryCriteriaEx criteria = parseQuery(request);

        Page<java.util.Map<?,?>> page = tWorkOrderService.queryWorkorderReport(criteria,pageable);
        JSONArray array = new JSONArray();

        for(java.util.Map<?,?> order: page.getContent()) {
            JSONObject obj = new JSONObject();
            obj.put("orderCode", order.get("orderCode")); //编码
            obj.put("customerName",order.get("customerName")); //客户名称1
            obj.put("major", order.get("major"));
            obj.put("level", order.get("level"));
            obj.put("realServiceTime", order.get("realServiceTime"));
            obj.put("taskTitle", order.get("taskTitle"));
            obj.put("taskAddr", order.get("taskAddr"));
            obj.put("money", Long.valueOf((String)order.get("realServiceTime"))*((BigInteger)order.get("customerCost")).intValue());
            obj.put("evaluateTime", DateUtil.parseDateToStr((java.util.Date)order.get("evaluateTime"), "yyyy-MM-dd"));
            array.add(obj);
        }

        return new ResponseEntity(PageUtil.toPageWithContent(page,array),HttpStatus.OK);
    }
}